package cn.framework.filter;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.RequestUtils;
import org.apache.struts2.dispatcher.FilterDispatcher;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.framework.constant.SessionConstant;
import cn.framework.exception.NeedLoginException;
import cn.framework.filter.data.NeedLoginUrl;





public class LoginFilter implements Filter {
	
	

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session=request.getSession();
        ServletContext context=session.getServletContext();
        WebApplicationContext spring=WebApplicationContextUtils.getWebApplicationContext(context);
        String servletPath=RequestUtils.getServletPath(request);
        
        NeedLoginUrl needLoginUrl=(NeedLoginUrl) spring.getBean("needLoginUrl");
        String loginUrl=context.getContextPath()+needLoginUrl.getLogin();
        List<String> roleUrls=needLoginUrl.getUrls();
        for (String roleUrl : roleUrls) {
			if(isNeedLogin(roleUrl, servletPath) &&session.getAttribute(needLoginUrl.getLoginSession())==null){
				session.setAttribute(SessionConstant.SESSION_MSG,NeedLoginException.MSG);
				response.sendRedirect(loginUrl);
			}
		}
        filterChain.doFilter(request, response);
	}
	
	public static boolean isNeedLogin(String roleUrl,String url){
		String targerURL=StringUtils.replace(url, "//", "/");
		boolean result=Pattern.compile(roleUrl).matcher(targerURL).find();
		return result;
	}
	
	public static void main(String[] args) {
		System.out.println(isNeedLogin("/demo/areaDemo*", "/demo/areaDemo.jsp"));
	}

	public void destroy() {
		
		
	}

	public void init(FilterConfig arg0) throws ServletException {
			
	}
}
